// /modules/settingModule/pages/address/list/index.js
//引入获取列表的api
import {reqAddressList,reqDelAddress} from '../../../../../api/address'
//引入关闭滑块的behavior
import {swipeCellBehavior} from '../../../../../behaviors/swipeCell'
const app = getApp()
Page({
  behaviors:[swipeCellBehavior],
  // 页面的初始数据
  data: {
    addressList: [1, 2, 3],
    
  },

  //点击时触发，将地址数据传给全局变量后传回订单页面
  changeAddress(event){
    const id = event.currentTarget.dataset.id
    // console.log(this.flag);
    if (this.flag === '1') {
      //如果是从订单列表跳转，flag为1,赋值当前选择的地址
      const address = this.data.addressList.find(item=>item.id === id)
      app.globalData.address = address
      console.log('跳转回');
      wx.navigateBack()
    }

  },


  async onShow(){
    //每次获得地址列表
    this.getAddressList()
  },

  //删除收货地址列表
  async delAddress(event){
    //解构出id
    console.log(event);
    const {id} = event.currentTarget.dataset
    //提示用户是否删除
    const res= await wx.modal({
      content:"是否删除地址？"
    })
    //如果用户点击确认
    if (res) {
     const res= await reqDelAddress(id)
     if (res) {
       wx.toast({title:"已删除"})
       //更新页面数据
       this.getAddressList()
     }
    }
  },
  //获取收货地址列表数据
  async getAddressList(){
    const res = await reqAddressList()
    // console.log(res);
    this.setData({
      addressList:res.data
    })
  },

  // 去编辑页面
  toEdit(event) {
    //解构出点击修改按钮时对应的id值
    const {id} = event.currentTarget.dataset
    //通过api去往修改页面
    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  onLoad(options){
    //默认进入时清除地址
    app.globalData.address = {}
    //接收从其他页面传来的参数
    //当flag=1时，即为从订单页面选择地址传入
    const {flag} = options
    this.flag = flag
    console.log(this.flag,'load');

  }
})
